export function isDef(v) {
	return v !== undefined && v !== null
}

/**
 * Remove an item from an array.
 */
export function remove(arr, item) {
	if (arr.length) {
		const index = arr.indexOf(item)
		if (index > -1) {
			return arr.splice(index, 1)
		}
	}
}

export function isRegExp(v) {
	return _toString.call(v) === '[object RegExp]'
}

/**
 * 判断是否为空
 * @param {any} obj 需要判断的值
 * @param {object} option 选项,ignoreBlank(忽略字符串中的空格或数组中的undefined和null项)
 * @returns {boolean} 是否为空
 * 例:
 * isEmpty('')  返回true
 * isEmpty('    ')  返回false
 * isEmpty('    ',{ignoreBlank:true})  返回true
 * isEmpty([])  返回true
 * isEmpty([undefined,null])  返回false
 * isEmpty([undefined,null],{ignoreBlank:true})  返回true
 */
export function isEmpty(obj, option = {ignoreBlank: false}) {
	if (obj === undefined || obj === null) {
		return true
	} else if (typeof obj === 'string') {
		if (option.ignoreBlank) {
			return obj === '' || obj.length <= 0 || obj.replace(/\s/g, '').length <= 0
		} else {
			return obj === '' || obj.length <= 0
		}
	} else if (isArray(obj)) {
		if (option.ignoreBlank) {
			return obj.filter(i => !isEmpty(i)).length <= 0
		} else {
			return obj.length <= 0
		}
	} else if (typeof obj === 'object' && option.ignoreBlank) {
		return isEmpty(Object.keys({}))
	} else {
		return false
	}
}

export function notEmpty(obj, option = {ignoreBlank: false}) {
	return !isEmpty(obj, option)
}

/**
 * 数组去重
 * @param arr
 * @returns {any[]|*[]}
 */
export function distinct(arr) {
	if (notEmpty(arr) && isArray(arr)) {
		return Array.from(new Set(arr))
	}
	return []
}

export function randomString(length) {
	let str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
	let result = ''
	for (let i = length; i > 0; --i)
		//根据需要的长度做循环
		//先对字符串集合str随机排列，再随机输出拼接
		result += str[Math.floor(Math.random() * str.length)]
	return result;
}

export function snake2Camel(str, capLower) {
	let s = str.replace(/[-_](\w)/g, function (x) {
		return x.slice(1).toUpperCase()
	})
	s = s.replace(/^\w/, function (x) {
		return capLower ? x.toLowerCase() : x.toUpperCase()
	})
	return s
}

export function isArray(item) {
	if (item === null || item === undefined)
		return false
	return Object.prototype.toString.call(item) === '[object Array]';
}

export function camel2Snake(str) {
	return str.replace(/([A-Z])/g, '-$1').toLowerCase()
}

export function priceFormat(num, n) {
	n = n || 2;
	let symbol = ",";
	if (num === null) return num;
	if (typeof num !== 'number') throw new TypeError('num参数应该是一个number类型');
	if (n < 0) throw new Error('参数n不应该小于0');
	let hasDot = parseInt(num) != num;//这里检测num是否为小数，true表示小数
	let m = (n != undefined && n != null) ? n : 1;
	num = m == 0 ? num.toFixed(m) + '.' : hasDot ? (n ? num.toFixed(n) : num) : num.toFixed(m);
	symbol = symbol || ',';
	num = num.toString().replace(/(\d)(?=(\d{3})+\.)/g, function (match, p1) {
		return p1 + symbol;
	});
	if (n == 0 || (!hasDot && !n)) {//如果n为0或者传入的num是整数并且没有指定整数的保留位数，则去掉前面操作中的小数位
		num = num.substring(0, num.indexOf('.'));
	}
	return num;
}

export function sleep(delay) {
	return new Promise((resolve) => setTimeout(resolve, delay))
}

export function isEqual(a, b) {
	if (a === undefined && b === undefined) return true
	if ((a === undefined && b !== undefined) || (a !== undefined && b === undefined)) return false

	let aProps = Object.getOwnPropertyNames(a)
	let bProps = Object.getOwnPropertyNames(b)
	if (aProps.length !== bProps.length) {
		console.log('isEqual', a, b, false)
		return false
	}
	for (let i = 0; i < aProps.length; i++) {
		let propName = aProps[i]

		let propA = a[propName]
		let propB = b[propName]
		if ((typeof (propA) === 'object')) {
			console.log('isEqual', a, b, !!this.isEqual(propA, propB))
			return !!this.isEqual(propA, propB)
		} else if (propA !== propB) {
			console.log('isEqual', a, b, false)
			return false
		}
	}
	console.log('isEqual', a, b, true)
	return true
}

export function animateCSS(element, animation, prefix = 'animate__') {
	return new Promise((resolve, reject) => {
		try {
			const animationName = `${prefix}${animation}`
			const node = document.querySelector(element)
			if (node) {
				node.classList.add(`${prefix}animated`, animationName)

				// When the animation ends, we clean the classes and resolve the Promise
				node.addEventListener(
					'animationend',
					(event) => {
						event.stopPropagation()
						node.classList.remove(`${prefix}animated`, animationName)
						resolve('Animation ended')
					},
					{once: true}
				)
			}
		} catch (e) {
			reject(e)
		}
	})
}

export function setQueryToUrl(url, ref, value) {
	let str = "";
	if (url.includes('?'))
		str = url.substr(url.indexOf('?') + 1);
	else
		return url + "?" + ref + "=" + value;
	let result = "";
	let setparam = "";
	let arr;
	let modify = "0";

	if (str.includes('&')) {
		arr = str.split('&');

		arr.forEach(i => {
			if (i.split('=')[0] === ref) {
				setparam = value;
				modify = "1";
			} else {
				setparam = i.split('=')[1];
			}
			result = result + i.split('=')[0] + "=" + setparam + "&";
		})

		result = result.substr(0, result.length - 1);

		if (modify === "0")
			if (result === str)
				result = result + "&" + ref + "=" + value;
	} else {
		if (str.includes('=')) {
			arr = str.split('=');

			if (arr[0] === ref) {
				setparam = value;
				modify = "1";
			} else {
				setparam = arr[1];
			}
			result = arr[0] + "=" + setparam;
			if (modify === "0")
				if (result === str)
					result = result + "&" + ref + "=" + value;
		} else
			result = ref + "=" + value;
	}
	return url.substr(0, url.indexOf('?')) + "?" + result;
}

export function isMobileTerminal() {
	let ua = navigator.userAgent,
		isWindowsPhone = /(?:Windows Phone)/.test(ua),
		isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
		isAndroid = /(?:Android)/.test(ua),
		isFireFox = /(?:Firefox)/.test(ua),
		// isChrome = /(?:Chrome|CriOS)/.test(ua),
		// 平板
		isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox &&
			/(?:Tablet)/.test(ua)),
		// 苹果手机
		isPhone = /(?:iPhone)/.test(ua) && !isTablet,
		// PC端
		isPc = !isPhone && !isAndroid && !isSymbian && !isTablet;
	return !isPc
	// return {
	// 	isTablet: isTablet,
	// 	isPhone: isPhone,
	// 	isAndroid: isAndroid,
	// 	isPc: isPc
	// }
}

export function objectToQueryString(obj) {
	const tempArray = [];
	for (const item in obj) {
		if (item && obj[item] !== undefined && obj[item] !== null) {
			tempArray.push(`${item}=${obj[item]}`);
		}
	}
	return tempArray.join('&');
}


const _toString = Object.prototype.toString
